package com.example.updateUtile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXResult;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.example.net.NetRequest;
import com.example.util.XMLContentHandler;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class UpdateManager {
	private final String VERSON_Url="http://112.124.0.70:8088/huashangService/verson.xml";//http://112.124.0.70:8080/huashangService/verson.xml
	private String curVersion;
	private String newVersion;
	private int curVersionCode;
	private int newVersionCode;
	private String updateInfo;
	private UpdateCallback callback;
	private Context ctx;
	private int progress;  
	private Boolean hasNewVersion;
	private Boolean canceled;

	//��Ÿ���APK�ļ���·��
	public static final String UPDATE_DOWNURL = "http://www.hsxxw.cn/index.php?appdownload/android";
	//��Ÿ���APK�ļ���Ӧ�İ汾˵��·��
	//public static final String UPDATE_CHECKURL = "http://www.www.baidu.com/test_update/update_version.txt";
	public static final String UPDATE_APKNAME = "HuaShangApp.apk";
	//public static final String UPDATE_VERJSON = "ver.txt";
	public static final String UPDATE_SAVENAME = "华商学习网.apk";
	private static final int UPDATE_CHECKCOMPLETED = 1;
	 private static final int UPDATE_DOWNLOADING = 2; 
	 private static final int UPDATE_DOWNLOAD_ERROR = 3; 
	 private static final int UPDATE_DOWNLOAD_COMPLETED = 4; 
	 private static final int UPDATE_DOWNLOAD_CANCELED = 5;

	 //�ӷ�����������apk����ļ���
	 private String savefolder = Environment.getExternalStorageDirectory().toString()+"/innerDisk/";
	 //private String savefolder = "/sdcard/";
		//public static final String SAVE_FOLDER =Storage. // "/mnt/innerDisk";
	public UpdateManager(Context context, UpdateCallback updateCallback) {
		ctx = context;
		callback = updateCallback;
		//savefolder = context.getFilesDir();
		canceled = false;
		getCurVersion();
	}
	
	public String getNewVersionName()
	{
		return newVersion;
	}
	
	public String getUpdateInfo()
	{
		return updateInfo;
	}

	private void getCurVersion() {
		try {
			PackageInfo pInfo = ctx.getPackageManager().getPackageInfo(
					ctx.getPackageName(), 0);
			curVersion = pInfo.versionName;
			curVersionCode = pInfo.versionCode;
		} catch (NameNotFoundException e) {
			Log.e("update", e.getMessage());
			curVersion = "1.1.1000";
			curVersionCode = 111000;
		}

	}

	URLConnection  connection = null;
	InputStream is = null;
	public void checkUpdate() {		
		hasNewVersion = false;
		new Thread(){
			@Override
			public void run() {
                    try {
                    	URL url = new URL(VERSON_Url);
                        // 打开连接,。会返回HttpsURLConnection 对象
                        HttpURLConnection httpsURLConnection = (HttpURLConnection) url
                                        .openConnection();
                        // 现在是使用HTTP协议请求服务器的数据
                        // 所以要设置请求方式
						httpsURLConnection.setRequestMethod("GET");
						  // 设置 超时时间 为5秒
	                    httpsURLConnection.setConnectTimeout(5 * 1000);
	                    // 通过输入流获取网络xml内容
	                    // 取得输入流
	                    SAXParserFactory factory=SAXParserFactory.newInstance();  
	                    //得到sax的解析器  
	                    SAXParser saxParser=factory.newSAXParser();  
	                    InputStream is=httpsURLConnection.getInputStream();
	                    XMLContentHandler handlerService=new XMLContentHandler();  
	                   
	                    //XMLReader xmlReader=saxParser.getXMLReader();
	                    //xmlReader.setContentHandler(handlerService);
	                    //创建handler对象  
	                    saxParser.parse(is, handlerService); 
	                   
	 	                    newVersionCode = handlerService.getVerinfos().get(0).getVersionCode();
          					newVersion = handlerService.getVerinfos().get(0).getVersionName();
          					updateInfo =handlerService.getVerinfos().get(0).getDescribe();
          					if(newVersionCode>curVersionCode){
          					hasNewVersion=true;
          					}else{
          						hasNewVersion=false;
          					}
					} catch (IOException e) {
						Log.i("error","IOException"+e.getMessage());
	                    newVersionCode = -1;
						newVersion = "";
						updateInfo = "";
					} catch (SAXException e) {
						e.printStackTrace();
						Log.i("error","IOException"+e.getMessage());
	                    newVersionCode = -1;
						newVersion = "";
						updateInfo = "";
					} catch (ParserConfigurationException e) {
						e.printStackTrace();
						Log.i("error","IOException"+e.getMessage());
	                    newVersionCode = -1;
						newVersion = "";
						updateInfo = "";
					}
				updateHandler.sendEmptyMessage(UPDATE_CHECKCOMPLETED);
			};
		}.start();

	}

	public void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		
		intent.setDataAndType(
				Uri.fromFile(new File(savefolder, UPDATE_SAVENAME)),
				"application/vnd.android.package-archive");
		ctx.startActivity(intent);
	}
	public void downloadPackage() 
	{
		new Thread() {			
			 @Override  
		        public void run() {  
		            try {  
		                URL url = new URL(UPDATE_DOWNURL);  
		                HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
		                conn.connect();  
		                int length = conn.getContentLength();  
		                InputStream is = conn.getInputStream();  
		                File ApkFile = null;  
		                try {  
		                	ApkFile = new File(savefolder);  
		                    if (!ApkFile.exists()) {  
		                    	ApkFile.mkdir();  
		                    }  
		                } catch (Exception e) {  
		          
		                }  
		                 ApkFile = new File(savefolder,UPDATE_SAVENAME);
		                 FileOutputStream fos = new FileOutputStream(ApkFile);  
		                int count = 0;  
		                byte buf[] = new byte[512];  
		                  
		                do{  
		                    int numread = is.read(buf);  
		                    count += numread;  
		                    progress =(int)(((float)count / length) * 100);  
		                   
		                    updateHandler.sendMessage(updateHandler.obtainMessage(UPDATE_DOWNLOADING)); 
		                    if(numread <= 0){      
		                    	updateHandler.sendEmptyMessage(UPDATE_DOWNLOAD_COMPLETED);
		                        break;  
		                    }  
		                    fos.write(buf,0,numread);  
		                }while(!canceled);  
		                if(canceled)
		                {
		                	updateHandler.sendEmptyMessage(UPDATE_DOWNLOAD_CANCELED);
		                }
		                fos.close();  
		                is.close();  
		            } catch (MalformedURLException e) {  
		                e.printStackTrace(); 
		                
		                updateHandler.sendMessage(updateHandler.obtainMessage(UPDATE_DOWNLOAD_ERROR,e.getMessage()));
		            } catch(IOException e){  
		                e.printStackTrace();  
		                
		                updateHandler.sendMessage(updateHandler.obtainMessage(UPDATE_DOWNLOAD_ERROR,e.getMessage()));
		            }  
		              
		        } 
		}.start();
	}

	public void cancelDownload()
	{
		canceled = true;
	}
	
	Handler updateHandler = new Handler() 
	{
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case UPDATE_CHECKCOMPLETED:
				
				callback.checkUpdateCompleted(hasNewVersion, newVersion);
				break;
			case UPDATE_DOWNLOADING:
				
				callback.downloadProgressChanged(progress);
				break;
			case UPDATE_DOWNLOAD_ERROR:
				
				callback.downloadCompleted(false, msg.obj.toString());
				break;
			case UPDATE_DOWNLOAD_COMPLETED:
				
				callback.downloadCompleted(true, "");
				break;
			case UPDATE_DOWNLOAD_CANCELED:
				
				callback.downloadCanceled();
			default:
				break;
			}
		}
	};
	public interface UpdateCallback {
		public void checkUpdateCompleted(Boolean hasUpdate,
				CharSequence updateInfo);
		public void downloadProgressChanged(int progress);
		public void downloadCanceled();
		public void downloadCompleted(Boolean sucess, CharSequence errorMsg);
	}

}
